package com.spzx.product.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.excel.util.ListUtils;
import com.spzx.product.domain.Category;
import com.spzx.product.service.CategoryService;
import org.springframework.beans.BeanUtils;


import java.util.List;
import java.util.stream.Collectors;

//不能@Component,@Component:变为单例
public class ExcelCategoryListener<CategoryExcelVo> extends AnalysisEventListener<CategoryExcelVo> {

    //直接注入@Autowired是单实例;可以通过构造传递
    private CategoryService categoryService;
    public ExcelCategoryListener(CategoryService categoryService){
        this.categoryService = categoryService;
    }
    private static final int BATCH_COUNT = 100;//设置条数为100条

    private List<CategoryExcelVo> cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);
    @Override
    public void invoke(CategoryExcelVo o, AnalysisContext analysisContext) {
        cachedDataList.add(o);
        if (cachedDataList.size() >= BATCH_COUNT){//达到一百条
            saveData();//添加到数据库
            cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);
        }
    }


    //添加数据
    private void saveData() {
        //List<CategoryExcelVo> ---> List<Category>
        List<Category> collect = cachedDataList.stream().map(categoryExcelVo -> {
            Category category = new Category();
            BeanUtils.copyProperties(categoryExcelVo, category);
            return category;
        }).collect(Collectors.toList());
        categoryService.saveBatch(collect);
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {//最后执行这个代码且最后不够100条数据时执行
        saveData();
    }
}
